import React from 'react';
import { Redirect, Link, withRouter, SessionModelState } from 'umi';
import { connect } from 'react-redux';

import styles from './index.less';
import { LOGINED_USER_SESSION } from '@/configs/constants';
import Store from '@/utils/store';
import { LoadPanel, Popup } from 'devextreme-react';
import { getUrlByName } from '@/utils/configsReader';

let portal_system_url = getUrlByName('portal_system_url');

interface IProps {
  session: SessionModelState;
  loading: boolean;
  dispatch: any;
  history: any;
  location: any;
}
class LoginView extends React.Component<IProps, any> {
  constructor(props: IProps) {
    super(props);
  }

  componentDidMount() {
    let token = this.props.location.query.token as string;
    if (token) {
      token = token.replace('Bearer ', '');
      Store.set(LOGINED_USER_SESSION, { token });
      this.getUserProfile(token);
    }
  }

  render() {
    const {
      loading,
      session: { userSession },
    } = this.props;

    if (userSession?.profile) {
      return <Redirect to="/" />;
    }

    portal_system_url = 'http://127.0.0.1:8000/demo/remoteLogin';

    return (
      <>
        <LoadPanel
          message={'用户身份验证中...'}
          visible={loading}
          // position={{ of: '#tips' }}
        />
        {!loading && (
          <Popup
            width={'552'}
            height={'440'}
            closeOnOutsideClick={false}
            title={'统一登录'}
            showTitle={false}
            showCloseButton={false}
            visible={loading === false}
            onHiding={() => null}
            className={styles['remote-login-popup']}
          >
            <iframe
              title="统一登录"
              src={`${portal_system_url}`}
              className={styles['portal_iframe']}
              scrolling="no"
            />
          </Popup>
        )}
      </>
    );
  }

  /**
   * 用户已在Portal门户网站登录,现在带着token过来.需要获取用户权限.
   */
  getUserProfile = (token: string) => {
    this.props.dispatch({ type: 'session/getUserProfile', payload: { token } });
  };

  redirectToPortal = () => {
    this.props.history.push(portal_system_url);
  };
}

const mapStateToProps = (state: any) => {
  const session: SessionModelState = state.session;
  return {
    session,
    loading: state.loading.global && state.loading.models.session, // dvaJs自带的loading(每个model共用一个)
  };
};

const mapDispatchToProps = (dispatch: any) => {
  return {
    dispatch,
  };
};

export default withRouter(
  connect(mapStateToProps, mapDispatchToProps)(LoginView),
);
